package com.sfzd5.exam;

import android.text.TextUtils;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import timber.log.Timber;

public class FileLoggingTree extends Timber.Tree {
    String CacheDiaPath;
    public FileLoggingTree(String cacheDiaPath){
        this.CacheDiaPath = cacheDiaPath;
    }

    @Override
    protected void log(int priority, @Nullable String tag, @NotNull String message, @Nullable Throwable t) {
        if (TextUtils.isEmpty(CacheDiaPath)) {
            return;
        }
        File file = new File(CacheDiaPath + "/log.txt");
        Log.v("dyp", "file.path:" + file.getAbsolutePath() + ",message:" + message);
        FileWriter writer = null;
        BufferedWriter bufferedWriter = null;
        try {
            writer = new FileWriter(file, true);
            bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write("\n<TimberLog>\n");
            bufferedWriter.write("\nTime:");
            bufferedWriter.write(new Date().toString());
            bufferedWriter.write("\npriority:");
            bufferedWriter.write(priority);
            if(tag!=null && !tag.isEmpty()){
                bufferedWriter.write("\ntag:");
                bufferedWriter.write(tag);
            }
            bufferedWriter.write(message);
            if(t!=null){
                bufferedWriter.write("\nThrowable:\n");
                PrintWriter printWriter = new PrintWriter(bufferedWriter);
                t.printStackTrace(printWriter);
            }
            bufferedWriter.write("\n</TimberLog>\n");
            bufferedWriter.flush();

        } catch (IOException e) {
            Log.v("dyp", "存储文件失败");
            e.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
